const getBrowser = require('../browser/init');
const DB = require('../db/config');

main();

// 调度函数
async function main() {
  const browser = await getBrowser();
  const page = await browser.newPage();
  const url = getUrl(1);
  await page.goto(url);
  const bookPage = await getBookPage(page);
  for (let i = 1; i < bookPage.count; i++) {
    const url = getUrl(i);
    await page.goto(url);
    await getBookInfoByPage(page);
  }
}
//获取URl
function getUrl(pageNum) {
  return `http://book.zongheng.com/store/c0/c0/b0/u0/p${pageNum}/v9/s9/t0/u0/i1/ALL.html`;
}

// 获取最大页数、书籍数
async function getBookPage(page) {
  return await page.$eval('.pagenumber', el => {
    const count = el.getAttribute('count');
    const total = el.getAttribute('total');
    return {
      count,
      total,
    };
  });
}
// 获取书名、详情页地址
async function getbookName_url(page) {
  return await page.$$eval('.bookbox .bookimg', els => {
    return els.map(v => {
      const detailUrl = v.querySelector('a').getAttribute('href');
      const imgUrl = v.querySelector('img').getAttribute('src');
      const name = v.querySelector('img').getAttribute('alt');
      return { name, detailUrl, imgUrl };
    });
  });
}
// 获取每页数据
async function getBookInfoByPage(page) {
  const bookInfo = await getbookName_url(page);
  for (let i = 0; i < bookInfo.length; i++) {
    const sql = 'INSERT INTO bookinfo VALUES (NULL,?,?,?)';
    const value = [bookInfo[i].name, bookInfo[i].imgUrl, bookInfo[i].detailUrl];
    try {
      await DB.query(sql, value).catch(err => {
        throw err;
      });
      console.log(`${value[0]}插入成功!!!`);
    } catch (error) {
      console.log(error);
      return;
    }
  }
}
